package com.petShop.controllers;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.petShop.dao.CartDao;
import com.petShop.dao.UserDao;
import com.petShop.models.Cart;
import com.petShop.models.Userinfo;
import com.petShop.util.MD5Utils;
import com.petShop.util.MyTool;

@Controller
@Transactional
@RequestMapping("/login")
public class LoginController {
	@Autowired
	UserDao userDao;
	@Autowired
	CartDao cartDao;
	@RequestMapping(method=RequestMethod.GET)
	public ModelAndView get(){
		ModelAndView mav = new ModelAndView("/login/login");
		return mav;
	}
	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView post(@RequestParam String username,@RequestParam String password,
			HttpSession session){
		ModelAndView mav = new ModelAndView();
		Userinfo userinfo = userDao.selectUserByName(username);
		if(userinfo!=null&&userinfo.getPassword().equals(MD5Utils.md5Password(password))){
			session.setAttribute("username", username);
			
			//获取购物车数量
			List<Cart> carts = cartDao.selectCarts(userinfo.getUserId());	
			session.setAttribute("allCount", MyTool.getCartAllcount(carts));
			
			
			String returnUrl = (String) session.getAttribute("returnUrl");
			//System.out.println("login "+returnUrl);
			if(returnUrl==null){
				mav.setViewName("redirect:/");
			}else{
				mav.setViewName("redirect:"+returnUrl);
			}
			
		}else{
			mav.addObject("errorMsg","用户名或密码错误");
			mav.setViewName("/login/login");
		}
		return mav;
	}
}
